//
//  MyCollectionInstitutionVC.swift
//  Venus
//
//  Created by qurongxiang on 2018/9/8.
//  Copyright © 2018年 zhaowang. All rights reserved.
//

import UIKit
import MJRefresh
private let cellID = "cellID"

class MyCollectionInstitutionVC: UIViewController {
    
    fileprivate lazy var tableView : UITableView = {
        let tableView = UITableView(frame: CGRect.zero)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(UINib(nibName: "HomeTableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
        return tableView
    }()
    
    var modelArr : [SchoolModel] =  [SchoolModel]()
    var currentPage:Int = 1 //当前页数
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupUI()
        loadData()
    }
}



// MARK: - 遵守上拉 下拉协议
extension MyCollectionInstitutionVC: RefreshControl {
    func refreshingActionFooter(refreshControl: MJRefreshAutoNormalFooter) {
        refreshControl.beginRefreshing()
        
        let userModel = UserInfo.shareInstance.userModel()
        let dict:String = ["longitude":userModel.longitude.count == 0 ? "1":userModel.longitude,
                           "latitude":userModel.latitude.count == 0 ? "1":userModel.latitude,
                           "pageNo":String(currentPage),
                           "pageSize":"10"
            ].formatApi()
        
        let range = dict.index(dict.startIndex, offsetBy: 1)..<dict.endIndex
        let url = kHost + kqueryCollectionInstitutionList + "".apiF(time: "1", sign: "2") + "&" + dict[range]
        TempNetTool.post(url, parameters: nil, progress: nil, success: { [weak self](result) in
            guard let resultDict = result as? [String : NSObject] else { return }
            guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
            if dataArray.count == 0 {
                return
            }
            let ma = SchoolModel.tmSpeelBreakModelArr(dataArray) as! [SchoolModel]
            if ma.count < 10 {
                self?.tableView.mj_footer.endRefreshingWithNoMoreData()
            }else {
                self?.tableView.mj_footer.resetNoMoreData()
            }
            self?.modelArr = (self?.modelArr)! + ma
            self?.currentPage =  (self?.currentPage)! + 1
            self?.tableView.reloadData()
            self?.tableView.mj_footer.endRefreshing()
        }) {(error) in
            
        }
    }
    
    
    func refreshingAction(refreshControl: MJRefreshNormalHeader) {
        refreshControl.beginRefreshing()
        loadData()
    }
    
    fileprivate func loadData() {
        currentPage = 1
        self.modelArr.removeAll()
        self.tableView.reloadData()
        let userModel = UserInfo.shareInstance.userModel()
        let dict:String = ["longitude":userModel.longitude.count == 0 ? "1":userModel.longitude,
                           "latitude":userModel.latitude.count == 0 ? "1":userModel.latitude,
                           "pageNo":"1",
                           "pageSize":"10"
            ].formatApi()
        
        let range = dict.index(dict.startIndex, offsetBy: 1)..<dict.endIndex
        let url = kHost + kqueryCollectionInstitutionList + "".apiF(time: "1", sign: "2") + "&" + dict[range]
        TempNetTool.post(url, parameters: nil, progress: nil, success: { [weak self](result) in
            self?.tableView.mj_header.endRefreshing()
            guard let resultDict = result as? [String : NSObject] else { return }
            guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
            if dataArray.count == 0 {
                self?.showEmptyDataView()
                return
            }
            self?.currentPage = 2
            self?.modelArr = SchoolModel.tmSpeelBreakModelArr(dataArray) as! [SchoolModel]
            self?.tableView.reloadData()
            if (self?.modelArr.count)! < 10 {
                self?.tableView.mj_footer.endRefreshingWithNoMoreData()
            }else {
                self?.tableView.mj_footer.resetNoMoreData()
            }
        }) { [weak self] (error) in
            self?.showNetworkErrorView(action: #selector(self?.networkError))
        }
    }
    
    @objc func networkError() {
        loadData()
    }
}




// MARK:- 代理
extension MyCollectionInstitutionVC:UITableViewDelegate , UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.modelArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView .dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! HomeTableViewCell
        cell.configModel(model: modelArr[indexPath.item], index: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 96
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = SchoolDetailViewController()
        let model = modelArr[indexPath.item]
        vc.schoolID = "\(model.id)"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension MyCollectionInstitutionVC  {
    
    
    func setupUI() {
        view.backgroundColor = UIColor.white
        self.title = "我的预约"
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.bottom.right.equalToSuperview()
        }
        setupRefreshControl(scrollView: self.tableView, target: self)
        setupRefreshFootControl(scrollView:  self.tableView, target: self)
    }
}
